import React, { useEffect, useMemo, useState } from "react";
import { ContainerRow, StyledContainer } from "./styled";
import { BorderBox7, Decoration6, ScrollRankingBoard, WaterLevelPond } from '@jiaminghi/data-view-react';
import LineCharts from "@/components/LineCharts/LineCharts";
import { Descriptions } from "@arco-design/web-react";


export const Title = (props) => {
    const { title, style } = props;
    return (
        <div style={{
            height: '24px',
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'flex-start',
            marginBottom: '12px',
        }}>
            <Decoration6 color={[ '#3491FA', '#27066E' ]} style={{ width: '24px', height: '24px', marginRight: '12px', ...(style || {}) }}/>
            { title }
        </div>
    )
}

interface IProps {
    city: string;
    data: any;
}

const StationDetail = (props: IProps) => {

    const { city, data } = props;
    const [ stationList, setStationList ] = useState<any>([]);
    const [ selectedStation, setSelectedStation ] = useState<string>('');
    const [ jsonData, setJsonData ] = useState<any>([]);

    const powerData = useMemo(() => {
        console.log(stationList);
        const { temperature, voltage, current } = stationList.find((st) => st.name === selectedStation)?.power || { temperature: 0, voltage: 0, current: 0 };
        return {
            temperature: {
                data: [temperature, temperature * 0.6],
                shape: 'roundRect',
                formatter: '{value}℃'
            },
            voltage: {
                data: [voltage, voltage * 0.6],
                shape: 'roundRect',
                formatter: '{value}V'
            },
             current: {
                data: [current, current * 0.6],
                shape: 'roundRect',
                formatter: '{value}A'
             }
        };
    }, [ stationList, selectedStation ]);

    const renderDeviceList = useMemo(() => {
        return {
            data: (stationList?.find((st) => st.name === selectedStation)?.deviceList || []).map((device) => {
                const { name, NormalOperationRate, state } = device;
                return {
                    name: `<div>
                        <span style="margin-right: 4px">${ name }</span>
                        <span
                            style="
                                border-radius: 2px;
                                width: max-content;
                                font-size: 12px;
                                padding: 1px 8px;
                                background: ${state ? '#00B42A' : '#F53F3F'};
                                color: ${state ? '#E8FFEA' : '#FFECEB'};
                            "
                        >${state ? '正常' : '异常'}</span>
                    </div>`,
                    value: NormalOperationRate,
                };
            })
        }
    }, [ selectedStation ]);

    const chartData = useMemo(() => {
        const dataComponents = data.citys[city].data;
        return Object.keys(dataComponents).map((type) => {
            return {
                name: type,
                data: dataComponents[type].map((port) => {
                    return {
                        name: port.name,
                        type: 'line',
                        smooth: true,
                        showSymbol: false,
                        areaStyle: {
                            opacity: 0.1
                        },
                        data: port.data,
                    }
                }),
            }
        });
    }, [ jsonData ]);

    const onStationSelected = (event) => {
        const domPath = event?.path || [];
        for(const dom of domPath) {
            const name = dom.getAttribute('data-name');
            if (name) {
                setSelectedStation(name);
                break;
            }
        }
    }

    useEffect(() => {
        const stList = data?.citys[city]?.stationList;
        setStationList(stList);
        setSelectedStation(stList?.[0]?.name || '');

        document.querySelector('#stationList')?.addEventListener('click', onStationSelected);

        return () => {
            document.querySelector('#stationList')?.removeEventListener('click', onStationSelected);
        }
    }, [ city, data ])

    return (
        <StyledContainer overflow="auto">
            <ContainerRow data-sub="true" height="300px" style={{ marginBottom: '12px', width: 'calc(100% - 12px)' }}>
                <StyledContainer style={{ width: 'calc(30% - 12px)', marginRight: '12px' }}>
                    <BorderBox7 className="decorate" style={{ width: '100%' }}>
                        <Title title="台站选择"/>
                        <StyledContainer style={{ overflowY: 'scroll', paddingRight: '12px', height: 'calc(100% - 36px)' }} id="stationList">
                            {
                                stationList?.map((station, index) => {
                                    return <span key={`station-${index}`} data-type="descriptions" data-name={station.name}>
                                        <Descriptions
                                            data-name={station.name}
                                            className={`${station.name === selectedStation ? 'station-selected' : 'station-normal'}`}
                                            style={{ margin: '0px 0px 12px 12px', cursor: 'pointer' }}
                                            colon=' :'
                                            layout='inline-horizontal'
                                            title={station.name}
                                            data={[
                                                { label: '台站IP', value: station.IP },
                                                { label: '异常出现次数(月)', value: station.abnMonthTotal },
                                                { label: '设备数量', value: station.deviceList.length },
                                            ]} 
                                        />
                                    </span>
                                })
                            }
                        </StyledContainer>
                    </BorderBox7>
                </StyledContainer>
                <StyledContainer style={{ width: 'calc(30% - 12px)', marginRight: '12px' }}>
                    <BorderBox7 className="decorate" style={{ width: '100%', height: '300px' }}>
                        <Title title="电源信息"/>
                        <ContainerRow height="100%">
                            <WaterLevelPond config={powerData.temperature} style={{width: 'calc(33.3% - 12px)', height: 'calc(100% - 36px)', marginRight: '12px'}} />
                            <WaterLevelPond config={powerData.voltage} style={{width: 'calc(33.3% - 12px)', height: 'calc(100% - 36px)', marginRight: '12px'}} />
                            <WaterLevelPond config={powerData.current} style={{width: '33.3%', height: 'calc(100% - 36px)'}} />
                        </ContainerRow>
                    </BorderBox7>
                </StyledContainer>
                <BorderBox7 className="decorate" style={{ width: '40%' }}>
                    <Title title="台站设备列表"/>
                    <ScrollRankingBoard config={renderDeviceList} style={{ width: '100%', height: "calc(100% - 36px)"}} />
                </BorderBox7>
            </ContainerRow>
            {
                chartData?.map((chart, index) => {
                    return (
                        <ContainerRow key={`chart-${index}`} height="230px" style={{ marginBottom: '12px', width: 'calc(100% - 12px)' }}>
                            <BorderBox7 className="decorate" style={{ width: '100%' }}>
                                <Title title={chart.name}/>
                                <LineCharts id={`chart-${index}`}  style={{ height: 'calc(100% - 16px)' }} data={chart.data}/>
                            </BorderBox7>
                        </ContainerRow>
                    )
                })
            }
        </StyledContainer>
    )
}


export default StationDetail;